package com.example.administrator.trains;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.Timer;
import java.util.TimerTask;

import static com.example.administrator.trains.R.id.time;

public class SocketService extends Service {
    public static Timer timer = new Timer();
    public static Intent SocketServiceIntent;

    private SocketBinder sockerBinder = new SocketBinder();
    public static TimerTask task = null;


    @Override
    public IBinder onBind(Intent intent) {
        return sockerBinder;
    }

    public class SocketBinder extends Binder {
        /*返回SocketService 在需要的地方可以通过ServiceConnection获取到SocketService  */
        public SocketService getService() {
            return SocketService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("SocketService","onCreate");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("SocketService","onStartCommand");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (Socket.mClient == null) {
                }
                sendBeatData();
            }
        }).start();

        return super.onStartCommand(intent, flags, startId);
    }

    /*定时发送数据*/
    private void sendBeatData() {
        if (timer == null) {
            timer = new Timer();
        }

        if (task == null) {
            task = new TimerTask() {
                @Override
                public void run() {
                    try {
                        byte[] data = Socket.connector.package_heart_data(Socket.connector.HEART_CMD_TYPE,
                                Socket.connector.HEART_CMD);
                        Socket.connector.send(data);
                    } catch (IOException e) {
                    }
                }
            };
        }

        timer.schedule(task, 0, 2000);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("SocketService", "onDestroy");
    }
}
